package com.mjk.common.core.drpc;

import com.mjk.common.core.drpc.conver.StringArrayToMapConverter;
import com.mjk.common.core.drpc.conver.StringArrayToStringConverter;
import org.apache.dubbo.config.spring.ServiceBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;

import java.util.Map;
/**
 * 解决@Service注解配置parameters参数时无法将String[]转化成Map<String,String>的bug
 *
 */
public class ServiceParameterBeanPostProcessor  implements PriorityOrdered {
    @Override
	public int getOrder() {
		return Ordered.LOWEST_PRECEDENCE;
	}



	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
		if (bean instanceof ServiceBean) {
			PropertyValue propertyValue = pvs.getPropertyValue("parameters");
			if(null != propertyValue) {
				ConversionService conversionService = getConversionService();
				Object obj = propertyValue.getValue();
				if (null != obj) {
					Class clazz = obj.getClass();
					if (conversionService.canConvert(clazz, Map.class)) {
						Map parameters = conversionService.convert(obj, Map.class);
						propertyValue.setConvertedValue(parameters);
					}
				}
			}
		}
		return pvs;
	}

	private ConversionService getConversionService() {
	        DefaultConversionService conversionService = new DefaultConversionService();
	        conversionService.addConverter(new StringArrayToStringConverter());
	        conversionService.addConverter(new StringArrayToMapConverter());
	        return conversionService;
	    }
}
